<?php

// Simple Captcha Generator

if (!isset($_SESSION)) {
  session_start();
}

function generate_captcha($len){
	$word="";
	for($i=0;$i<$len;$i++){
		do{
			$c = chr(rand(ord("a"),ord("z") ));
		}while(!ctype_alnum($c));
		$word .= $c;
	}
	return $word;
}

function check_captcha($captcha){
	$check = false;
    $sid = session_id(); 
    error_log("SID: $sid");
    if(isset($_SESSION["captcha"])){
    	$captcha = $_SESSION["captcha"];
        error_log("captcha ".$_SESSION["captcha"]);
        error_log("key ".$_SESSION["key"]);
    	if(isset($_REQUEST["key"])){
    	   $test = $_REQUEST["key"];
    	   if($captcha==$test)
    	       $check=true;	
        }
    }
	return $check;
}

error_log("request: ". serialize($_REQUEST));

if(isset($_REQUEST['check'])){
    error_log("check");
    $check=false;
    if(isset($_REQUEST['key'])){
        $check = check_captcha($_REQUEST['key']);
    }
    echo ($check)? 'true' : 'false';
} else if(isset($_REQUEST['image'])){
	header("Content-type: image/png");
    $key = generate_captcha($_REQUEST['image']);
    // add session id
    $sid = session_id(); 
	$_SESSION["captcha"]=$key;
    error_log("captcha: $key");
	$width = 200;
	$height = 70;
	$font = "./resources/FreeSerif.ttf";
	$im = imagecreatetruecolor($width, $height);
	$white = imagecolorallocate($im, 255, 255, 255);
	$black = imagecolorallocate($im, 0, 0, 0);
    $gray = imagecolorallocate($im, 100, 100, 100);
	imagefilledrectangle($im, 0, 0, $width-1, $height-1, $white);
	imagerectangle($im, 1, 1, $width-1, $height-1, $black);
	$x=20;
    $y=10;
    // dots
    for($i=0;$i<100;$i++){
        $d = rand(1, 5);
        imagefilledellipse($im, rand($d, $width-$d), rand($d, $height-$d), $d, $d, $gray);
    }
	for($i=0;$i<strlen($key);$i++){
		$angle = rand(-70,70);
		$size = rand(12,35);
		imagettftext($im, $size, $angle, $x, 50-$y, $black, $font, substr($key,$i,1));
		$x += $size;
		$y = rand(0, 20);
	}
	imagepng($im);
	imagedestroy($im);
}

?>